package com.gin.no_gay_alliance.listener;

import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.gin.nga.callback.JsonCallback;
import com.gin.nga.client.NgaClient;
import com.gin.nga.exception.NgaClientException;
import com.gin.nga.exception.NgaException;
import com.gin.nga.method.NukeApi;
import com.gin.nga.params.nuke.TopicRecommendParam;
import com.gin.nga.response.body.nuke.TopicRecommendBody;
import com.gin.no_gay_alliance.R;
import com.gin.no_gay_alliance.app.MyApplication;
import com.gin.no_gay_alliance.utils.MyHandler;
import com.gin.no_gay_alliance.viewmodel.ReplyItem;

/**
 * @author : ginstone
 * @version : v1.0.0
 * @since : 2023/8/24 17:44
 **/
public class AgreeOnclickListener extends RequestButtonOnClickListener {
    final MyHandler handler;
    final TextView tvAgreeCount;
    final ReplyItem replyItem;

    public AgreeOnclickListener(MyHandler handler, TextView tvAgreeCount, ReplyItem replyItem) {
        this.handler = handler;
        this.tvAgreeCount = tvAgreeCount;
        this.replyItem = replyItem;
    }

    @Override
    protected void load(View view) {
        int id = view.getId();
        // 先设置为黄色
        ImageView iv = (ImageView) view;
        iv.setImageResource(R.drawable.ic_agree_yellow);

        NgaClient client = MyApplication.getClient();
        NukeApi.topicRecommend(client, new TopicRecommendParam(replyItem.topicId, replyItem.replyId, id == R.id.iv_agree)).async(new JsonCallback<TopicRecommendBody>() {
            @Override
            public void onSuccess(TopicRecommendBody body) {
                handler.toast(body.getMessage());
                // 更新赞数
                replyItem.agreeCount += body.getValue();
                handler.post(() -> {
                    // 按钮恢复原状
                    iv.setImageResource(R.drawable.ic_agree);
                    // 修改界面数据
                    int newCount = Integer.parseInt(tvAgreeCount.getText().toString()) + body.getValue();
                    tvAgreeCount.setText(String.valueOf(newCount));
                });
                finish(view);
            }

            @Override
            public void handleException(NgaException e) {
                super.handleException(e);
                if (e instanceof NgaClientException) {
                    String message = ((NgaClientException) e).getReason().get(0);
                    handler.toast(message);
                    iv.setImageResource(R.drawable.ic_agree);
                    finish(view);
                }
            }
        });
    }

    @Override
    public void onLoading(View view) {
        handler.toast("正在请求中,请稍候..");
    }
}
